/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package aptech.semester.code.gui;

import aptech.semester.code.common.ApplicationCommon;
import aptech.semester.code.common.Constants;
import aptech.semester.code.conn.MyLib;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.swing.JFrame;

/**
 *
 * @author vi
 */
public class ConnectDatabase extends javax.swing.JInternalFrame {

    /**
     * Creates new form ConnectDatabase
     */
    public ConnectDatabase(JFrame mainPanel) {
        initComponents();
        setBounds(ApplicationCommon.getRectangleForCenter(mainPanel.getSize().width, mainPanel.getSize().height, this.getWidth(), this.getHeight()));
        loadPropeties();
        btnTestCnn.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtServerName = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtDBName = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnTestCnn = new javax.swing.JButton();
        lblMsg = new javax.swing.JLabel();

        setClosable(true);
        setTitle("Config Connection Database");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/database.png"))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel2.setText("Connect Database");

        jLabel3.setText("Server Name");

        jLabel4.setText("Database Name");

        txtDBName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDBNameActionPerformed(evt);
            }
        });

        jLabel5.setText("User Name");

        jLabel6.setText("Password");

        jLabel7.setText("Port");

        btnOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/save.png"))); // NOI18N
        btnOK.setText("Save");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/btn_cancel.png"))); // NOI18N
        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnTestCnn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/checked.png"))); // NOI18N
        btnTestCnn.setText("Test Connection");
        btnTestCnn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTestCnnActionPerformed(evt);
            }
        });

        lblMsg.setToolTipText("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(btnTestCnn)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnCancel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnOK))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel4)
                                .addComponent(jLabel3)
                                .addComponent(jLabel5)
                                .addComponent(jLabel6)
                                .addComponent(jLabel7))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblMsg)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtServerName)
                                    .addComponent(txtDBName)
                                    .addComponent(txtUsername)
                                    .addComponent(txtPassword)
                                    .addComponent(txtPort, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE))))))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jLabel2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addComponent(lblMsg)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtServerName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtDBName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOK)
                    .addComponent(btnCancel)
                    .addComponent(btnTestCnn))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtDBNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDBNameActionPerformed
        
    }//GEN-LAST:event_txtDBNameActionPerformed

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        saveConfig();
        lblMsg.setIcon(null);
        lblMsg.setText("");
        btnTestCnn.setEnabled(true);
        btnOK.setEnabled(false);
    }//GEN-LAST:event_btnOKActionPerformed

    private void btnTestCnnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestCnnActionPerformed
        btnOK.setEnabled(true);
        btnTestCnn.setEnabled(false);
        if(testConnection()) {
            lblMsg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/checked.png")));
            lblMsg.setText("Connect successfully !");
        } else {
            lblMsg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/delete.png")));
            lblMsg.setText("Connect failed !");
        }
    }//GEN-LAST:event_btnTestCnnActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        loadPropeties();
        lblMsg.setIcon(null);
        lblMsg.setText("");
    }//GEN-LAST:event_btnCancelActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JButton btnTestCnn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel lblMsg;
    private javax.swing.JTextField txtDBName;
    private javax.swing.JTextField txtPassword;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextField txtServerName;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
    private void loadPropeties() {
        
        Properties prop = new Properties();
    	InputStream input = null;
        try {
            String filename = Constants.PATH_FOLDER_CONFIG + Constants.NAME_FILE_CONFIG;
            File f = new File(filename);
            input = new FileInputStream(f);
            
            if (input == null) {
                System.out.println("Sorry, unable to find " + filename);
                
            } else {
                prop.load(input);
            
                
                String userName = prop.getProperty("username");
                String password = prop.getProperty("password");
                String port = prop.getProperty("port");
                String databaseName = prop.getProperty("database_name");
                String serverName = prop.getProperty("server_name");
                
                txtServerName.setText(serverName);
                txtDBName.setText(databaseName);
                txtPort.setText(port);
                txtUsername.setText(userName);
                txtPassword.setText(password);
                
            }
         
        } catch(IOException e) {
            
        }
    }
    
    private void saveConfig() {
        Properties prop = new Properties();
        OutputStream output = null;

        try {
            String filename = Constants.PATH_FOLDER_CONFIG + Constants.NAME_FILE_CONFIG;
            File f = new File(filename);
            
            if (f.exists()) {
                output = new FileOutputStream(f);

                // set the properties value
                prop.setProperty("server_name", txtServerName.getText());
                prop.setProperty("database_name", txtDBName.getText());
                prop.setProperty("port", txtPort.getText());
                prop.setProperty("username", txtUsername.getText());
                prop.setProperty("password", txtPassword.getText());

                // save properties to project root folder
                prop.store(output, null);
            }

        } catch (IOException io) {
            io.printStackTrace();
        } catch (Exception io) {
            
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    
    private boolean testConnection() {
        if (MyLib.getCN() != null) {
            return true;
        } else {
            return false;
        }
    }
}
